package tech.wetech.admin3.sys.service;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tech.wetech.admin3.controller.AooAnotherMeController;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.*;
import tech.wetech.admin3.sys.repository.AooAnotherMeRepository;
import tech.wetech.admin3.sys.repository.AooVirtualManRepository;
import tech.wetech.admin3.util.GetDateUtil;
import tech.wetech.admin3.util.HashUtil;
import tech.wetech.admin3.util.OrderUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service
public class AooVirtualManService {
  private final OssService ossService;
  private AooVirtualManRepository virtualManRepository;
  private AooPhoneCodeService phoneCodeService;
  private HashUtil hashUtil;
  private MsgCenterService msgCenterService;

  public AooVirtualManService(
    OssService ossService,
    AooVirtualManRepository virtualManRepository,
    AooPhoneCodeService phoneCodeService,
    HashUtil hashUtil,
    MsgCenterService msgCenterService
  ) {
    this.ossService = ossService;
    this.virtualManRepository = virtualManRepository;
    this.phoneCodeService = phoneCodeService;
    this.hashUtil = hashUtil;
    this.msgCenterService = msgCenterService;
  }

  @Transactional
  public AooVirtualMan upload(AooVirtualMan aooVirtualMan) {
    return virtualManRepository.save(aooVirtualMan);
  }

  public List<AooVirtualMan> getAllData() {
    return virtualManRepository.findAll();
  }

  // 仅获取已支付的虚拟人
  public List<AooVirtualMan> findByPaid(boolean paid) {
    return virtualManRepository.findByPaid(paid);
  }

  public List<AooVirtualMan> findByStatus(Integer status) {
    return virtualManRepository.findByStatus(status);
  }

  public AooVirtualMan findById(Integer id) {
    return virtualManRepository.findById(id).orElse(null);
  }

  public AooVirtualMan findByUuid(UUID uuid) {
    return virtualManRepository.findByUuid(uuid);
  }

  public List<AooVirtualMan> findByEmail(String email) {
    return virtualManRepository.findByEmail(email);
  }

  public List<AooVirtualMan> findByDigitalNameContaining(String digitalName) {
    return virtualManRepository.findByDigitalNameContaining(digitalName);
  }

  @Transactional
  public boolean resetStatus(UUID uuid, Integer newStatus, String checkDesc) {
    AooVirtualMan virtualMan = virtualManRepository.findByUuid(uuid);
    if (virtualMan != null) {
      // 检查新状态是否与旧状态相同
      if (virtualMan.getStatus().equals(newStatus)) {
        // 如果状态相同，抛出一个RuntimeException或者自定义的异常
        throw new IllegalStateException("更新的状态与原状态相同，无需更新。");
      }

      virtualMan.setStatus(newStatus);
      virtualManRepository.save(virtualMan);
      String name = virtualMan.getDigitalName();
      String email = virtualMan.getEmail();
      if (newStatus == 2) {
        // 审核通过的消息
        msgCenterService.createMessage("数字人身份创建成功", "您提交创建的虚拟创造数字人" + name + "数字身份已发放，您可在数字人身份创建页面点击“已拥有的认证”查看它的数字证书。", email);
      } else if (newStatus == 3) {
        // 审核驳回的消息
        msgCenterService.createMessage("数字人身份创建失败", "您提交创建的虚拟创造数字人" + name + "经审核驳回，审核意见为" + checkDesc + "；您可确认相关内容后，点击“数字人身份创建”重新提交申请。", email);
      }
      return true;
    } else {
      return false;
    }
  }

  @Transactional
  public AooVirtualMan createVirtualMan(
    String owner,
    String ownerIdNo,
    String email,
    String digitalName,
    String mobile,
    String vericode,
    String feature,
    String purpose,
    MultipartFile[] modelFiles,
    MultipartFile[] images,
    String signFileUrl
  ) {
    if (images.length > 5) {
      throw new AooUserException("图片不能超过5张");
    }
    if (modelFiles != null && modelFiles.length > 5) {
      throw new AooUserException("模型文件不能超过5个");
    }

    List<String> imageUrls = new ArrayList<>();
    List<String> imageUrlHashes = new ArrayList<>();
    for (MultipartFile image : images) {
      if (image.getSize() > 10 * 1024 * 1024) {
        throw new AooUserException("图片不能大于10MB");
      }
      imageUrls.add(ossService.uploadImage(image));
      imageUrlHashes.add(hashUtil.getFileHash(image));
    }

    List<String> modelFileUrls = new ArrayList<>();
    List<String> modelFileHashes = new ArrayList<>();
    if (modelFiles != null) {
      for (MultipartFile modelFile : modelFiles) {
        if (modelFile.getSize() > 200 * 1024 * 1024) {
          throw new AooUserException("模型文件不能大于200MB");
        }
        modelFileUrls.add(ossService.uploadImage(modelFile));
        modelFileHashes.add(hashUtil.getFileHash(modelFile));
      }
    }

//    // 查重
//    List queryResult = virtualManRepository.findByEmailAndDigitalName(email, digitalName);
//    if (queryResult.size() > 0) {
//      throw new AooUserException("您已有该名字的虚拟人");  //  一个用户 禁止 虚拟人同名
//    }

    boolean flag = phoneCodeService.verifyCode(mobile, vericode);
    if (!flag) {
      throw new AooUserException("验证码错误或已过期");
    }

    Gson gson = new Gson();
    AooVirtualMan aooVirtualMan = new AooVirtualMan();
    aooVirtualMan.setOwner(owner);
    aooVirtualMan.setOwnerIdNo(ownerIdNo);
    aooVirtualMan.setEmail(email);
    aooVirtualMan.setDigitalName(digitalName);
    aooVirtualMan.setMobile(mobile);
    aooVirtualMan.setFeature(feature);
    aooVirtualMan.setPurpose(purpose);
    aooVirtualMan.setCreateDate(GetDateUtil.getYyyyMMddHHmmss());
    aooVirtualMan.setSignFileUrl(signFileUrl);
    aooVirtualMan.setOutTradeNo(OrderUtil.generateOrderNumber("vm"));
    aooVirtualMan.setImageUrls(gson.toJson(imageUrls));
    aooVirtualMan.setImageHashes(gson.toJson(imageUrlHashes));
    aooVirtualMan.setModelFileUrls(gson.toJson(modelFileUrls));
    aooVirtualMan.setModelFileHashes(gson.toJson(modelFileHashes));

    AooVirtualMan savedData = upload(aooVirtualMan);
    if (savedData != null && savedData.getId() != null) { // 假设savedData有一个ID字段来确认持久化
      phoneCodeService.deleteCode(mobile);  //  操作后删除验证码，使失效
      System.out.println("保存虚拟人 AooVirtualMan---" + savedData);
      return savedData;
    } else {
      // 保存失败的情况
      throw new AooUserException("提交失败， 请重试");
    }
  }

  public AooVirtualMan admin_update(UUID uuid, String key, boolean value, String vericode) {
    boolean flag = phoneCodeService.admin_VerifyCode(vericode);
    if (!flag) {
      throw new IllegalArgumentException("admin 验证码错误或已过期");
    }

    AooVirtualMan virtualMan = virtualManRepository.findByUuid(uuid);
    if (virtualMan == null) {
      throw new AooUserException("用户不存在");
    }

    switch (key) {
      case "paid":
        virtualMan.setPaid(value);
        break;
//      case "avatarUrl":
//        user.setAvatarUrl(value);
//        break;
//      case "password":
//        user.setPassword(passwordEncoder.encode(value));
//        break;
      default:
        throw new IllegalArgumentException("不支持的key: " + key);
    }
    return virtualManRepository.save(virtualMan);
  }


  public boolean isImageHashExist(String hash) {
    var result = virtualManRepository.findByImageHashesContaining(hash);
    System.out.println("virtualMan: " + virtualManRepository.findByImageHashesContaining(hash));
    return result != null && !result.isEmpty();
  }

  public boolean isModelFileHashExist(String hash) {
    var result = virtualManRepository.findByModelFileHashesContaining(hash);
    System.out.println("virtualMan: " + result);
    return result != null && !result.isEmpty();
  }
}

